<template>
  <el-dialog v-model="dialogVisible" :title="signInData.signName" width="800px" :close-on-click-modal="false"
    :show-close="true" @close="handleClose" class="sign-in-result">
    <div class="status-bar">
      <div class="status-text" :class="{ 'ended': state.isEnded }">
        {{ statusText }}
      </div>
      <div class="stats">
        <span>签到码：{{ signInData.signCode }}</span>
        <span>共计：{{ totalStudents }}</span>
        <span>已签到：{{ stats.signed }}</span>
        <span>未签到：{{ stats.unsigned }}</span>
        <span>迟到：{{ stats.late }}</span>
        <span>早退：{{ stats.leaveEarly }}</span>
        <span>请假：{{ stats.leave }}</span>
      </div>
      <el-button type="primary" link>
        <i class="el-icon-download"></i>
        导出
      </el-button>
    </div>

    <el-table :data="state.tableData" style="width: 100%">
      <el-table-column prop="studentId" label="学号" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column label="状态">
        <template #default="scope">
          <el-select v-model="scope.row.status" class="status-select" @change="() => handleStatusChange(scope.row)">
            <el-option label="未签到" value="未签到" />
            <el-option label="已签到" value="已签到" />
            <el-option label="迟到" value="迟到" />
            <el-option label="早退" value="早退" />
            <el-option label="请假" value="请假" />
          </el-select>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination background layout="prev, pager, next" :total="totalStudents" :page-size="10" :current-page="1" />
      <span class="page-info">共 {{ totalStudents }} 条</span>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, reactive } from 'vue'

const props = defineProps({
  signInData: {
    type: Object,
    required: true,
    default: () => ({
      signId: null,
      signName: '',
      signCode: '',
      endType: 2,
      startTime: 0,
      studentList: []
    })
  },
  sendMessage: {
    type: Function,
    required: true
  }
})

const emit = defineEmits(['close'])
const dialogVisible = ref(true)

// 状态管理
const state = reactive({
  tableData: computed(() => {
    // 每次 studentList 变化时重新计算表格数据
    return props.signInData.studentList.map(student => ({
      studentId: student.userId,
      name: student.userName,
      status: student.signStatus
    }))
  }),
  remainingTime: 0,
  isEnded: false,
  currentTimer: null
})

// 计算属性
const totalStudents = computed(() => props.signInData.studentList.length)

const stats = computed(() => ({
  signed: state.tableData.filter(item => item.status === '已签到').length,
  unsigned: state.tableData.filter(item => item.status === '未签到').length,
  late: state.tableData.filter(item => item.status === '迟到').length,
  leaveEarly: state.tableData.filter(item => item.status === '早退').length,
  leave: state.tableData.filter(item => item.status === '请假').length
}))

const statusText = computed(() => {
  if (state.isEnded) return '已结束'
  const minutes = Math.floor(state.remainingTime / 60)
  const seconds = state.remainingTime % 60
  return `${minutes}:${seconds.toString().padStart(2, '0')}`
})

// 倒计时方法
const cleanupTimer = () => {
  if (state.currentTimer) {
    clearInterval(state.currentTimer)
    state.currentTimer = null
  }
}

const startCountdown = () => {
  // 清理现有定时器
  cleanupTimer()

  // 重置状态
  state.isEnded = false
  state.remainingTime = 0

  // 根据endType设置倒计时时间（分钟转秒）
  const totalTime = props.signInData.endType * 60

  if (totalTime === 0) {
    // endType为0表示手动关闭
    return
  }

  // 计算已经过去的时间（秒）
  const elapsedSeconds = Math.floor((new Date().getTime() - props.signInData.startTime) / 1000)

  // 计算剩余时间
  state.remainingTime = Math.max(0, totalTime - elapsedSeconds)

  // 如果已经超时，直接标记为结束
  if (state.remainingTime <= 0) {
    state.isEnded = true
    return
  }

  // 启动新定时器
  state.currentTimer = setInterval(() => {
    if (state.remainingTime > 0) {
      state.remainingTime--
    } else {
      state.isEnded = true
      cleanupTimer()
    }
  }, 1000)
}

// 组件挂载时启动倒计时
onMounted(() => {
  startCountdown()
})

// 组件卸载时清理
onUnmounted(() => {
  cleanupTimer()
})

const handleClose = () => {
  cleanupTimer()
  emit('close')
}

// 监听签到状态变化的方法
const handleStatusChange = (row) => {
  // 发送状态更新消息
  props.sendMessage({
    type: 'UPDATE_SIGN_STATUS',
    data: {
      signId: props.signInData.signId,
      userId: row.studentId,
      status: row.status
    }
  })
}
</script>

<style scoped>
.sign-in-result {
  :deep(.el-dialog) {
    background-color: white;
    border-radius: 8px;
  }

  :deep(.el-dialog__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #eee;
  }

  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.status-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.status-text {
  color: #409eff;
  /* 倒���时时显示蓝色 */
  margin-right: 20px;
  font-size: 14px;
}

.status-text.ended {
  color: #ff4d4f;
  /* 结束时显示红色 */
}

.stats {
  flex: 1;
  display: flex;
  gap: 20px;
  color: #666;
}

.status-select {
  width: 100px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.page-info {
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  padding: 10px 20px;
  border-top: 1px solid #eee;
}
</style>